using System;
using System.Data;
using System.Linq;

namespace ECatalog.Models.Locations
{
    public class LocationRepository : ILocationRepository
    {
        public void AddLocation(Location location)
        {
            using (var db = new DbContainer())
            {
                try
                {
                    db.Locations.Add(location);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                }
            }
        }

        public Location ExistLocation(int modelId, int shopId)
        {
            using (var db = new DbContainer())
            {
                var l = db.Locations.SingleOrDefault(loc => loc.ModelId == modelId && loc.ShopId == shopId);
                if (l != null)
                {
                    return l;
                }
                return null;
            }
        }

        public void SaveLocation(Location location)
        {
            using (var db = new DbContainer())
            {
                db.Entry(location).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        public Location GetLocation(int shopId, int modelId)
        {
            using (var db = new DbContainer())
            {
                return db.Locations.SingleOrDefault(loc => loc.ShopId == shopId && loc.ModelId == modelId);
            }
        }
    }
}